package com.opticon.vaadinR.tools.density;

import com.opticon.vaadinR.core.RFilter;
import com.opticon.vaadinR.core.RSource;
import com.opticon.vaadinR.core.conf.CoreConfiguration;
import com.opticon.vaadinR.core.constants.RConstants;
import com.opticon.vaadinR.exceptions.RVaadinException;
import com.opticon.vaadinR.interfaces.RResultHandler;
import com.opticon.vaadinR.runnable.RExecution;
import com.opticon.vaadinR.runnable.RRunner;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;

/**
 * This class is a
 */
public class DensityExecution extends RExecution {
    private static Logger logger = Logger.getLogger(DensityExecution.class);

    protected String iMean = "" + 5;
    protected String iSessionID = "NA";
    protected RResultHandler iRResultHandler = null;

    public DensityExecution(RResultHandler aRResultHandler) {
        iRResultHandler = aRResultHandler;
    }

    @Override
    public void run() {

        try {
            File lFile = new File(CoreConfiguration.getRScriptDefault());
            iRSource = new RSource(lFile);

            iRFilter = new RFilter();
            iRFilter.add("mean", iMean);
            iRFilter.add(RConstants.WORKSPACE, CoreConfiguration.getTmpDir().getCanonicalPath());
            iRFilter.add(RConstants.TASKID, "" + System.currentTimeMillis());
            iRFilter.add(RConstants.SESSIONID, iSessionID);
            iRSource.filter(iRFilter);

            logger.debug("starting R");
            iRRunner = new RRunner(iRSource);
            iRRunner.run();

            logger.debug("loading results");
            iRResultHandler.loadRResults(iRFilter);

            iObservable.setChanged();
            notifyObservers();

            logger.debug("processing results");


        } catch (IOException e) {
            throw new RVaadinException(e);
        }
    }


    public void setMean(String aMean) {
        iMean = aMean;
    }

    public void setSessionID(String aSessionID) {
        iSessionID = aSessionID;
    }

}
